package com.scheduled;

import com.gavel.utils.StringUtils;
import com.google.gson.Gson;
import com.jd.open.api.sdk.DefaultJdClient;
import com.jd.open.api.sdk.JdClient;
import com.jd.open.api.sdk.domain.supplier.ProductManagementService.response.find.ItemPicApplyDto;
import com.jd.open.api.sdk.domain.supplier.ProductManagementService.response.find.MyProductInfoDto;
import com.jd.open.api.sdk.request.supplier.VcItemPrimaryPicCreateRequest;
import com.jd.open.api.sdk.request.supplier.VcItemProductsFindRequest;
import com.jd.open.api.sdk.response.supplier.VcItemPrimaryPicCreateResponse;
import com.jd.open.api.sdk.response.supplier.VcItemProductsFindResponse;
import com.jd.service.JDPictureService;
import com.mrobuy.jd.JdClientFactory;
import com.mrobuy.jd.api.Jos;
import com.mrobuy.jd.sdk.request.VcItemPrimaryPicAppliesFindRequest;
import com.mrobuy.jd.sdk.response.VcItemPrimaryPicAppliesFindResponse;
import com.mrobuy.jdvc.dao.JDAccountDao;
import com.mrobuy.jdvc.dao.VCItemDao;
import com.mrobuy.jdvc.dao.VCProductDao;
import com.mrobuy.jdvc.dao.VCProductInfoDao;
import com.mrobuy.jdvc.entity.*;
import com.mrobuy.util.CodeEncoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.List;

/**
 *  商品主图处理
 *
 */
@Component
public class PrimaryPicTask {

    private static Logger LOG = LoggerFactory.getLogger(PrimaryPicTask.class);

    @Autowired
    private VCProductInfoDao vcProductInfoDao;

    @Autowired
    private VCProductDao vcProductDao;

    @Autowired
    private VCItemDao vcItemDao;

    @Autowired
    private JDAccountDao jdAccountDao;

    @Autowired
    private JDPictureService jdPictureService;

    @Scheduled(fixedRate = 1000*60*60)
    public void reportCurrentTime() {
        //LOG.info("hello");

        if ( !TaskSwitch.PRIMARY_PIC.get() ) {
            return;
        }


        LOG.info("Task start...");

        List<JDAccount> accounts = jdAccountDao.list();

        if ( accounts!=null ) {
            for (JDAccount account : accounts) {

                LOG.info("{}", account);

                handlePrimaryPic(account);
            }
        }

        LOG.info("Task done.");

    }

    private void handlePrimaryPic(JDAccount account) {
        if ( account==null ) {
            return;
        }

        JdClient client = new DefaultJdClient(JdClientFactory.serverUrl, account.getAccess_token(), account.getAppkey(), account.getAppsecret());

        List<VCProductInfo> productInfos = vcProductInfoDao.list(account.getVccode(), 0);
        if ( productInfos != null ) {
            int index = 1;
            for (VCProductInfo productInfo : productInfos) {

                if (StringUtils.isNotBlank(productInfo.getPicApplyId())) {
                    continue;
                }

                LOG.info("{}. {}", index++,  productInfo);

                if (StringUtils.isBlank(productInfo.getPicApplyId())) {
                    VcItemPrimaryPicAppliesFindRequest request=new VcItemPrimaryPicAppliesFindRequest();
                    request.setPage(1);
                    request.setLength(50);
                    request.setWareId(productInfo.getWareId());
                    try {
                        VcItemPrimaryPicAppliesFindResponse response = client.execute(request);
                         ItemPicApplyDto[] results = response.getJosResultDto().getResult();
                        if ( results!=null && results.length > 0 ) {
                            for (com.jd.open.api.sdk.domain.supplier.ProductManagementService.response.find.ItemPicApplyDto result : results) {
                                productInfo.setPicApplyId(result.getApplyId());
                                productInfo.setApplyTime(result.getApplyTime());

                                productInfo.setState(result.getState());
                                productInfo.setBrandId(result.getBrandId());
                                productInfo.setBrandName(result.getBrandName());
                                productInfo.setCategoryId(result.getCategoryId());
                                productInfo.setCategoryName(result.getCategoryName());
                                vcProductInfoDao.update(productInfo);
                            }
                        }
                    } catch (Exception e) {
                        LOG.error("{}", e.getMessage());
                        e.printStackTrace();
                    }
                }

                // 如果没有提交过主图申请, 就提交主图申请
                if (StringUtils.isBlank(productInfo.getPicApplyId())) {
                    try {
                        primaryPicCreate(productInfo, client);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    private void primaryPicCreate(VCProductInfo productInfo, JdClient client) throws Exception {

        if ( productInfo==null || productInfo.getIsPrimary()==1 ) {
            return;
        }

        LOG.info("[Wareid: {}]{}: SALESTATE: " + productInfo.getSaleState() + "; ISPRIMARY: " + productInfo.getIsPrimary() + "; ISGAEA: " + productInfo.getIsGaea(), productInfo.getWareId(),  productInfo.getWareName() );


        List<VCItem> vcItems = vcItemDao.loadByWareId(productInfo.getWareId());
        if ( vcItems==null || vcItems.size()==0 ) {
            try {
                VCProduct vcProduct = Jos.itemProductGetClient(JdClientFactory.jdClient())
                        .setWareId(productInfo.getWareId())
                        .call();
                if ( vcProduct!=null ) {
                    vcProductDao.delete(productInfo.getWareId());
                    vcProductDao.insert(vcProduct);
                    vcItems = (vcProduct==null ? Collections.EMPTY_LIST : vcProduct.getVcItems());
                    for (VCItem vcItem : vcItems) {
                        vcItem.setVendor(productInfo.getVendorCode());
                        vcItemDao.insert(vcItem);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        if ( vcItems==null || vcItems.size()==0 ) {
            System.out.println("没有Item商品信息！");
            return;
        }

        LOG.info("Item: {}", vcItems.size());

        StringBuilder skuIds = new StringBuilder();
        StringBuilder skuImageList = new StringBuilder();
        StringBuilder skuImageListLucency = new StringBuilder();

        int i = 0;
        for (VCItem vcItem : vcItems) {
            i++;
            System.out.println("\t" + i + ". [" + vcItem.getSkuName() + "][" + vcItem.getSkuId() + "]: " + vcItem.getItemNum());

            List<String> itemPics = jdPictureService.getPictures(vcItem.getSkuId());
            if ( itemPics==null || itemPics.size()==0 ) {
                LOG.warn("[VC_ITEM_PIC][Sku: {}]缺少主图图片信息", vcItem.getSkuId());
                continue;
            }


            List<String> vcItemLucencyPics = jdPictureService.getLucencyPictures(vcItem.getSkuId());
            if ( vcItemLucencyPics==null || vcItemLucencyPics.size()==0 ) {
                LOG.warn("[VC_ITEM_PIC][Sku: {}]缺少主图透明图信息", vcItem.getSkuId());
                continue;
            }

            skuIds.append(vcItem.getSkuId()).append(",");

            for (String pic : itemPics) {
                // skuImageList.append(itemPic.getUrl().replace("http://img20.360buyimg.com/vc/", "")).append(";");
                skuImageList.append(pic.replace("http://img20.360buyimg.com/vc/", "")).append(";");
            }
            skuImageList.deleteCharAt(skuImageList.length()-1).append(",");

            // http://img30.360buyimg.com/n4
            skuImageListLucency.append(vcItemLucencyPics.get(0).replace("http://img20.360buyimg.com/vc/", "")).append(",");

        }

        if ( skuIds.length() == 0 ) {
            return;
        }


        skuIds.deleteCharAt(skuIds.length()-1);
        skuImageList.deleteCharAt(skuImageList.length()-1);
        skuImageListLucency.deleteCharAt(skuImageListLucency.length()-1);

        VcItemPrimaryPicCreateRequest request=new VcItemPrimaryPicCreateRequest();
        request.setSkuId(skuIds.toString());
        request.setImageList(skuImageList.toString());

        request.setSkuIdLucency(skuIds.toString());
        request.setImageListLucency(skuImageListLucency.toString());


        VcItemPrimaryPicCreateResponse response = client.execute(request);

        LOG.info("{}", new Gson().toJson(response));

        if ( response.getJosResultDto()==null ) {
            productInfo.setMessage(response.getMsg());
            vcProductInfoDao.update(productInfo);
            throw new Exception(response.getZhDesc());
        }

        productInfo.setSubmitTime(Calendar.getInstance().getTime());
        productInfo.setMessage(new Gson().toJson(response));
        if ( response.getJosResultDto().getSuccess() ) {
            productInfo.setMessage(response.getJosResultDto().getReturnMessage());
            productInfo.setPicApplyId(response.getJosResultDto().getSingleObj());
        }
        vcProductInfoDao.update(productInfo);
    }
}
